from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.hashers import make_password, check_password
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
import re
from datetime import datetime
from django.core.paginator import Paginator
from django.db.models import Q, Count, Sum

from .models import User, Book, BorrowRecord, Role, UserRole, Permission  # 包没有导入
from .decorators import require_auth, require_permission, require_role, PERMISSIONS, ROLES
from rest_framework import serializers

# Create your views here.

class TestUserView(View):
    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        print("token", token)
        if token is not None and token != '':
            user_list = User.objects.all()
            print(user_list, type(user_list))
            # 把对象类型转换为字典类型
            user_dict = user_list.values()
            print(user_dict, type(user_dict))
            # 解析字典类型 把字典类型转换为json串
            userList = list(user_dict)
            print(userList, type(user_list))
            # 响应给前台json串的数据
            return JsonResponse({'code': 200, 'info': '测试成功', 'data': userList})
            # 通过网页访问 localhost：5000/user/test
        else:
            return JsonResponse({'code': 200, 'info': '未授权没有访问权限'})


class JwtTestView(View):
    def get(self, request):
        user = User.objects.get(username="admin", password="123456")
        # jwt 处理函数
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 生成载荷的令牌
        # 把用户对象传递，获取该对象的属性值
        payload = jwt_payload_handler(user)
        # 将jwt获取的属性值 编译成json格式
        token = jwt_encode_handler(payload)
        print('token', token)
        return JsonResponse({'code': 200, 'info': '获取成功', 'token': token})


# 用户注册功能
class RegisterView(View):
    def post(self, request):
        try:
            # 获取注册数据
            username = request.POST.get('username')
            password = request.POST.get('password')
            email = request.POST.get('email')
            phonenumber = request.POST.get('phonenumber')
            
            # 数据验证
            if not username or not password:
                return JsonResponse({'code': 400, 'info': '用户名和密码不能为空'})
            
            if len(username) < 3 or len(username) > 20:
                return JsonResponse({'code': 400, 'info': '用户名长度必须在3-20个字符之间'})
            
            if len(password) < 6:
                return JsonResponse({'code': 400, 'info': '密码长度不能少于6个字符'})
            
            # 检查用户名是否已存在
            if User.objects.filter(username=username).exists():
                return JsonResponse({'code': 400, 'info': '用户名已存在'})
            
            # 邮箱验证
            if email:
                try:
                    validate_email(email)
                except ValidationError:
                    return JsonResponse({'code': 400, 'info': '邮箱格式不正确'})
                
                if User.objects.filter(email=email).exists():
                    return JsonResponse({'code': 400, 'info': '邮箱已被注册'})
            
            # 手机号验证
            if phonenumber:
                phone_pattern = re.compile(r'^1[3-9]\d{9}$')
                if not phone_pattern.match(phonenumber):
                    return JsonResponse({'code': 400, 'info': '手机号格式不正确'})
                
                if User.objects.filter(phonenumber=phonenumber).exists():
                    return JsonResponse({'code': 400, 'info': '手机号已被注册'})
            
            # 创建用户
            user = User.objects.create(
                username=username,
                password=make_password(password),  # 密码加密
                email=email,
                phonenumber=phonenumber,
                status=0,  # 0表示激活状态
                create_time=datetime.now().date(),
                update_time=datetime.now().date()
            )
            
            # 默认分配普通用户角色
            default_role, created = Role.objects.get_or_create(
                name=ROLES['USER'],
                defaults={
                    'description': '普通用户',
                    'permissions': [PERMISSIONS['BOOK_VIEW'], PERMISSIONS['BORROW_VIEW'], PERMISSIONS['BORROW_CREATE']]
                }
            )
            
            UserRole.objects.create(user=user, role=default_role)
            
            return JsonResponse({
                'code': 200, 
                'info': '注册成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phonenumber': user.phonenumber
                }
            })
            
        except Exception as e:
            print(f"注册错误: {e}")
            return JsonResponse({'code': 500, 'info': '注册失败，请稍后重试'})


# 登录操作
class LoginView(View):
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        if not username or not password:
            return JsonResponse({'code': 400, 'info': '用户名和密码不能为空'})
        
        try:
            user = User.objects.get(username=username)
            
            # 验证密码
            if not check_password(password, user.password):
                return JsonResponse({'code': 400, 'info': '用户名或密码错误'})
            
            # 检查用户状态
            if user.status != 0:
                return JsonResponse({'code': 400, 'info': '账户已被禁用，请联系管理员'})
            
            # 更新登录时间
            user.login_date = datetime.now().date()
            user.save()
            
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 生成载荷的令牌
            # 把用户对象传递，获取该对象的属性值
            payload = jwt_payload_handler(user)
            # 将jwt获取的属性值 编译成json格式
            token = jwt_encode_handler(payload)
        except User.DoesNotExist:
            return JsonResponse({'code': 400, 'info': '用户名或密码错误'})
        except Exception as e:
            print(f"登录错误: {e}")
            return JsonResponse({'code': 500, 'info': '登录失败，请稍后重试'})

        return JsonResponse({'code': 200, "token": token, "user": UserSerializers(user).data, 'info': '登录成功'})


# 用户管理API
class UserListView(View):
    """用户列表API"""
    @require_permission(PERMISSIONS['USER_VIEW'])
    def get(self, request):
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            search = request.GET.get('search', '')
            status = request.GET.get('status', '')
            
            # 构建查询条件
            users = User.objects.all()
            
            if search:
                users = users.filter(
                    Q(username__icontains=search) | 
                    Q(email__icontains=search) | 
                    Q(phonenumber__icontains=search)
                )
            
            if status != '':
                users = users.filter(status=int(status))
            
            # 按创建时间倒序排列
            users = users.order_by('-create_time')
            
            # 分页
            paginator = Paginator(users, page_size)
            user_page = paginator.get_page(page)
            
            # 序列化数据
            user_list = []
            for user in user_page:
                # 获取用户角色
                user_roles = UserRole.objects.filter(user=user)
                roles = []
                for user_role in user_roles:
                    roles.append({
                        'id': user_role.role.id,
                        'name': user_role.role.name,
                        'description': user_role.role.description
                    })
                
                user_list.append({
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phonenumber': user.phonenumber,
                    'imgurl': user.imgurl,
                    'login_date': user.login_date.strftime('%Y-%m-%d') if user.login_date else None,
                    'status': user.status,
                    'status_text': '激活' if user.status == 0 else '禁用',
                    'create_time': user.create_time.strftime('%Y-%m-%d') if user.create_time else None,
                    'update_time': user.update_time.strftime('%Y-%m-%d') if user.update_time else None,
                    'remark': user.remark,
                    'roles': roles
                })
            
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': {
                    'users': user_list,
                    'total': paginator.count,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages
                }
            })
            
        except Exception as e:
            print(f"获取用户列表错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取用户列表失败'})


class UserDetailView(View):
    """用户详情API"""
    @require_permission(PERMISSIONS['USER_VIEW'])
    def get(self, request, user_id):
        try:
            user = User.objects.get(id=user_id)
            
            # 获取用户角色
            user_roles = UserRole.objects.filter(user=user)
            roles = []
            for user_role in user_roles:
                roles.append({
                    'id': user_role.role.id,
                    'name': user_role.role.name,
                    'description': user_role.role.description,
                    'permissions': user_role.role.permissions
                })
            
            # 获取用户借阅统计
            borrow_stats = BorrowRecord.objects.filter(user=user).aggregate(
                total_borrows=Count('id'),
                current_borrows=Count('id', filter=Q(is_returned=False))
            )
            
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phonenumber': user.phonenumber,
                    'imgurl': user.imgurl,
                    'login_date': user.login_date.strftime('%Y-%m-%d') if user.login_date else None,
                    'status': user.status,
                    'status_text': '激活' if user.status == 0 else '禁用',
                    'create_time': user.create_time.strftime('%Y-%m-%d') if user.create_time else None,
                    'update_time': user.update_time.strftime('%Y-%m-%d') if user.update_time else None,
                    'remark': user.remark,
                    'roles': roles,
                    'borrow_stats': {
                        'total_borrows': borrow_stats['total_borrows'],
                        'current_borrows': borrow_stats['current_borrows']
                    }
                }
            })
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '用户不存在'})
        except Exception as e:
            print(f"获取用户详情错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取用户详情失败'})


class UserUpdateView(View):
    """更新用户信息API"""
    @require_permission(PERMISSIONS['USER_UPDATE'])
    def put(self, request, user_id):
        try:
            user = User.objects.get(id=user_id)
            
            # 获取更新数据
            email = request.POST.get('email')
            phonenumber = request.POST.get('phonenumber')
            imgurl = request.POST.get('imgurl')
            status = request.POST.get('status')
            remark = request.POST.get('remark')
            
            # 邮箱验证
            if email:
                try:
                    validate_email(email)
                except ValidationError:
                    return JsonResponse({'code': 400, 'info': '邮箱格式不正确'})
                
                # 检查邮箱是否被其他用户使用
                if User.objects.filter(email=email).exclude(id=user_id).exists():
                    return JsonResponse({'code': 400, 'info': '邮箱已被其他用户使用'})
                
                user.email = email
            
            # 手机号验证
            if phonenumber:
                phone_pattern = re.compile(r'^1[3-9]\d{9}$')
                if not phone_pattern.match(phonenumber):
                    return JsonResponse({'code': 400, 'info': '手机号格式不正确'})
                
                # 检查手机号是否被其他用户使用
                if User.objects.filter(phonenumber=phonenumber).exclude(id=user_id).exists():
                    return JsonResponse({'code': 400, 'info': '手机号已被其他用户使用'})
                
                user.phonenumber = phonenumber
            
            if imgurl is not None:
                user.imgurl = imgurl
            
            if status is not None:
                user.status = int(status)
            
            if remark is not None:
                user.remark = remark
            
            user.update_time = datetime.now().date()
            user.save()
            
            return JsonResponse({
                'code': 200,
                'info': '更新成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phonenumber': user.phonenumber
                }
            })
            
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '用户不存在'})
        except Exception as e:
            print(f"更新用户错误: {e}")
            return JsonResponse({'code': 500, 'info': '更新用户失败'})


class UserPasswordUpdateView(View):
    """更新用户密码API"""
    @require_permission(PERMISSIONS['USER_UPDATE'])
    def put(self, request, user_id):
        try:
            user = User.objects.get(id=user_id)
            
            old_password = request.POST.get('old_password')
            new_password = request.POST.get('new_password')
            
            if not old_password or not new_password:
                return JsonResponse({'code': 400, 'info': '旧密码和新密码不能为空'})
            
            # 验证旧密码
            if not check_password(old_password, user.password):
                return JsonResponse({'code': 400, 'info': '旧密码错误'})
            
            # 验证新密码长度
            if len(new_password) < 6:
                return JsonResponse({'code': 400, 'info': '新密码长度不能少于6个字符'})
            
            # 更新密码
            user.password = make_password(new_password)
            user.update_time = datetime.now().date()
            user.save()
            
            return JsonResponse({
                'code': 200,
                'info': '密码更新成功'
            })
            
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '用户不存在'})
        except Exception as e:
            print(f"更新密码错误: {e}")
            return JsonResponse({'code': 500, 'info': '更新密码失败'})


class UserStatusUpdateView(View):
    """更新用户状态API"""
    @require_permission(PERMISSIONS['USER_UPDATE'])
    def put(self, request, user_id):
        try:
            user = User.objects.get(id=user_id)
            
            status = request.POST.get('status')
            
            if status is None:
                return JsonResponse({'code': 400, 'info': '状态参数不能为空'})
            
            status = int(status)
            if status not in [0, 1]:
                return JsonResponse({'code': 400, 'info': '状态值无效（0-激活，1-禁用）'})
            
            # 不能禁用自己
            if user.id == request.user.id and status == 1:
                return JsonResponse({'code': 400, 'info': '不能禁用自己的账户'})
            
            user.status = status
            user.update_time = datetime.now().date()
            user.save()
            
            status_text = '激活' if status == 0 else '禁用'
            
            return JsonResponse({
                'code': 200,
                'info': f'用户状态已{status_text}',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'status': status,
                    'status_text': status_text
                }
            })
            
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '用户不存在'})
        except Exception as e:
            print(f"更新用户状态错误: {e}")
            return JsonResponse({'code': 500, 'info': '更新用户状态失败'})


class UserDeleteView(View):
    """删除用户API"""
    @require_permission(PERMISSIONS['USER_DELETE'])
    def delete(self, request, user_id):
        try:
            user = User.objects.get(id=user_id)
            
            # 不能删除自己
            if user.id == request.user.id:
                return JsonResponse({'code': 400, 'info': '不能删除自己的账户'})
            
            # 检查是否有未归还的借阅记录
            if BorrowRecord.objects.filter(user=user, is_returned=False).exists():
                return JsonResponse({'code': 400, 'info': '该用户有未归还的借阅记录，无法删除'})
            
            # 删除用户角色关联
            UserRole.objects.filter(user=user).delete()
            
            # 删除用户
            user.delete()
            
            return JsonResponse({
                'code': 200,
                'info': '用户删除成功'
            })
            
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '用户不存在'})
        except Exception as e:
            print(f"删除用户错误: {e}")
            return JsonResponse({'code': 500, 'info': '删除用户失败'})


class UserProfileView(View):
    """获取当前用户信息API"""
    @require_auth
    def get(self, request):
        try:
            user = request.user
            
            # 获取用户角色
            user_roles = UserRole.objects.filter(user=user)
            roles = []
            for user_role in user_roles:
                roles.append({
                    'id': user_role.role.id,
                    'name': user_role.role.name,
                    'description': user_role.role.description,
                    'permissions': user_role.role.permissions
                })
            
            # 获取用户借阅统计
            borrow_stats = BorrowRecord.objects.filter(user=user).aggregate(
                total_borrows=Count('id'),
                current_borrows=Count('id', filter=Q(is_returned=False))
            )
            
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phonenumber': user.phonenumber,
                    'imgurl': user.imgurl,
                    'login_date': user.login_date.strftime('%Y-%m-%d') if user.login_date else None,
                    'status': user.status,
                    'status_text': '激活' if user.status == 0 else '禁用',
                    'create_time': user.create_time.strftime('%Y-%m-%d') if user.create_time else None,
                    'update_time': user.update_time.strftime('%Y-%m-%d') if user.update_time else None,
                    'remark': user.remark,
                    'roles': roles,
                    'borrow_stats': {
                        'total_borrows': borrow_stats['total_borrows'],
                        'current_borrows': borrow_stats['current_borrows']
                    }
                }
            })
            
        except Exception as e:
            print(f"获取用户信息错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取用户信息失败'})


# 图书管理API
class BookListView(View):
    """图书列表API"""
    @require_auth
    def get(self, request):
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            search = request.GET.get('search', '')
            category = request.GET.get('category', '')
            
            # 构建查询条件
            books = Book.objects.all()
            
            if search:
                books = books.filter(
                    Q(title__icontains=search) | 
                    Q(author__icontains=search) | 
                    Q(description__icontains=search)
                )
            
            if category:
                books = books.filter(category=category)
            
            # 分页
            paginator = Paginator(books, page_size)
            book_page = paginator.get_page(page)
            
            # 序列化数据
            book_list = []
            for book in book_page:
                book_list.append({
                    'id': book.id,
                    'title': book.title,
                    'author': book.author,
                    'description': book.description,
                    'stock': book.stock,
                    'borrowed': book.borrowed,
                    'available': book.stock - book.borrowed,
                    'category': book.category
                })
            
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': {
                    'books': book_list,
                    'total': paginator.count,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages
                }
            })
            
        except Exception as e:
            print(f"获取图书列表错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取图书列表失败'})


# 热榜API - 根据借阅数量倒序分页展示
class BookHotRankingView(View):
    """图书热榜API - 根据借阅数量倒序排列"""
    @require_auth
    def get(self, request):
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            category = request.GET.get('category', '')
            time_range = request.GET.get('time_range', 'all')  # all, week, month
            
            # 构建查询条件
            books = Book.objects.all()
            
            # 按分类筛选
            if category:
                books = books.filter(category=category)
            
            # 根据时间范围筛选借阅记录
            if time_range != 'all':
                from datetime import timedelta
                now = datetime.now()
                
                if time_range == 'week':
                    start_date = now - timedelta(days=7)
                elif time_range == 'month':
                    start_date = now - timedelta(days=30)
                else:
                    start_date = None
                
                if start_date:
                    # 获取指定时间范围内的借阅记录
                    recent_borrows = BorrowRecord.objects.filter(
                        borrow_time__gte=start_date
                    ).values('book_id').annotate(
                        recent_borrowed_count=Count('id')
                    )
                    
                    # 创建图书ID到最近借阅次数的映射
                    recent_borrow_map = {item['book_id']: item['recent_borrowed_count'] for item in recent_borrows}
                    
                    # 为每本书添加最近借阅次数
                    for book in books:
                        book.recent_borrowed = recent_borrow_map.get(book.id, 0)
                    
                    # 按最近借阅次数倒序排列
                    books = sorted(books, key=lambda x: x.recent_borrowed, reverse=True)
                else:
                    # 按总借阅次数倒序排列
                    books = books.order_by('-borrowed')
            else:
                # 按总借阅次数倒序排列
                books = books.order_by('-borrowed')
            
            # 分页
            paginator = Paginator(books, page_size)
            book_page = paginator.get_page(page)
            
            # 序列化数据
            book_list = []
            for i, book in enumerate(book_page):
                # 计算排名（考虑分页）
                ranking = (page - 1) * page_size + i + 1
                
                book_data = {
                    'ranking': ranking,  # 排名
                    'id': book.id,
                    'title': book.title,
                    'author': book.author,
                    'description': book.description,
                    'stock': book.stock,
                    'borrowed': book.borrowed,
                    'available': book.stock - book.borrowed,
                    'category': book.category,
                    'borrow_rate': round((book.borrowed / book.stock * 100), 2) if book.stock > 0 else 0  # 借阅率
                }
                
                # 如果是按时间范围查询，添加最近借阅次数
                if time_range != 'all' and hasattr(book, 'recent_borrowed'):
                    book_data['recent_borrowed'] = book.recent_borrowed
                
                book_list.append(book_data)
            
            return JsonResponse({
                'code': 200,
                'info': '获取热榜成功',
                'data': {
                    'books': book_list,
                    'total': paginator.count,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages,
                    'time_range': time_range,
                    'category': category
                }
            })
            
        except Exception as e:
            print(f"获取图书热榜错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取图书热榜失败'})


# 分类热榜API
class CategoryHotRankingView(View):
    """分类热榜API - 按分类统计借阅数量"""
    @require_auth
    def get(self, request):
        try:
            # 获取查询参数
            time_range = request.GET.get('time_range', 'all')  # all, week, month
            limit = int(request.GET.get('limit', 10))  # 返回前N个分类
            
            # 构建查询条件
            if time_range != 'all':
                from datetime import timedelta
                now = datetime.now()
                
                if time_range == 'week':
                    start_date = now - timedelta(days=7)
                elif time_range == 'month':
                    start_date = now - timedelta(days=30)
                else:
                    start_date = None
                
                if start_date:
                    # 获取指定时间范围内的借阅记录，按分类统计
                    category_stats = BorrowRecord.objects.filter(
                        borrow_time__gte=start_date
                    ).values('book__category').annotate(
                        borrow_count=Count('id'),
                        book_count=Count('book', distinct=True)
                    ).filter(
                        book__category__isnull=False
                    ).exclude(
                        book__category=''
                    ).order_by('-borrow_count')[:limit]
                else:
                    category_stats = []
            else:
                # 按总借阅次数统计分类
                category_stats = Book.objects.values('category').annotate(
                    borrow_count=Sum('borrowed'),
                    book_count=Count('id')
                ).filter(
                    category__isnull=False
                ).exclude(
                    category=''
                ).order_by('-borrow_count')[:limit]
            
            # 序列化数据
            category_list = []
            for i, stat in enumerate(category_stats):
                category_list.append({
                    'ranking': i + 1,  # 排名
                    'category': stat['category'],
                    'borrow_count': stat['borrow_count'],
                    'book_count': stat['book_count'],
                    'avg_borrow_per_book': round(stat['borrow_count'] / stat['book_count'], 2) if stat['book_count'] > 0 else 0
                })
            
            return JsonResponse({
                'code': 200,
                'info': '获取分类热榜成功',
                'data': {
                    'categories': category_list,
                    'time_range': time_range,
                    'limit': limit
                }
            })
            
        except Exception as e:
            print(f"获取分类热榜错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取分类热榜失败'})


# 作者热榜API
class AuthorHotRankingView(View):
    """作者热榜API - 按作者统计借阅数量"""
    @require_auth
    def get(self, request):
        try:
            # 获取查询参数
            time_range = request.GET.get('time_range', 'all')  # all, week, month
            limit = int(request.GET.get('limit', 10))  # 返回前N个作者
            
            # 构建查询条件
            if time_range != 'all':
                from datetime import timedelta
                now = datetime.now()
                
                if time_range == 'week':
                    start_date = now - timedelta(days=7)
                elif time_range == 'month':
                    start_date = now - timedelta(days=30)
                else:
                    start_date = None
                
                if start_date:
                    # 获取指定时间范围内的借阅记录，按作者统计
                    author_stats = BorrowRecord.objects.filter(
                        borrow_time__gte=start_date
                    ).values('book__author').annotate(
                        borrow_count=Count('id'),
                        book_count=Count('book', distinct=True)
                    ).filter(
                        book__author__isnull=False
                    ).exclude(
                        book__author=''
                    ).order_by('-borrow_count')[:limit]
                else:
                    author_stats = []
            else:
                # 按总借阅次数统计作者
                author_stats = Book.objects.values('author').annotate(
                    borrow_count=Sum('borrowed'),
                    book_count=Count('id')
                ).filter(
                    author__isnull=False
                ).exclude(
                    author=''
                ).order_by('-borrow_count')[:limit]
            
            # 序列化数据
            author_list = []
            for i, stat in enumerate(author_stats):
                author_list.append({
                    'ranking': i + 1,  # 排名
                    'author': stat['author'],
                    'borrow_count': stat['borrow_count'],
                    'book_count': stat['book_count'],
                    'avg_borrow_per_book': round(stat['borrow_count'] / stat['book_count'], 2) if stat['book_count'] > 0 else 0
                })
            
            return JsonResponse({
                'code': 200,
                'info': '获取作者热榜成功',
                'data': {
                    'authors': author_list,
                    'time_range': time_range,
                    'limit': limit
                }
            })
            
        except Exception as e:
            print(f"获取作者热榜错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取作者热榜失败'})


class BookDetailView(View):
    """图书详情API"""
    @require_auth
    def get(self, request, book_id):
        try:
            book = Book.objects.get(id=book_id)
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': {
                    'id': book.id,
                    'title': book.title,
                    'author': book.author,
                    'description': book.description,
                    'stock': book.stock,
                    'borrowed': book.borrowed,
                    'available': book.stock - book.borrowed,
                    'category': book.category
                }
            })
        except Book.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '图书不存在'})
        except Exception as e:
            print(f"获取图书详情错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取图书详情失败'})


class BookCreateView(View):
    """创建图书API"""
    @require_permission(PERMISSIONS['BOOK_CREATE'])
    def post(self, request):
        try:
            title = request.POST.get('title')
            author = request.POST.get('author')
            description = request.POST.get('description', '')
            stock = request.POST.get('stock', 1)
            category = request.POST.get('category', '')
            
            if not title or not author:
                return JsonResponse({'code': 400, 'info': '书名和作者不能为空'})
            
            # 检查图书是否已存在
            if Book.objects.filter(title=title, author=author).exists():
                return JsonResponse({'code': 400, 'info': '该图书已存在'})
            
            book = Book.objects.create(
                title=title,
                author=author,
                description=description,
                stock=int(stock),
                category=category
            )
            
            return JsonResponse({
                'code': 200,
                'info': '创建成功',
                'data': {
                    'id': book.id,
                    'title': book.title,
                    'author': book.author
                }
            })
            
        except Exception as e:
            print(f"创建图书错误: {e}")
            return JsonResponse({'code': 500, 'info': '创建图书失败'})


class BookUpdateView(View):
    """更新图书API"""
    @require_permission(PERMISSIONS['BOOK_UPDATE'])
    def put(self, request, book_id):
        try:
            book = Book.objects.get(id=book_id)
            
            title = request.POST.get('title')
            author = request.POST.get('author')
            description = request.POST.get('description')
            stock = request.POST.get('stock')
            category = request.POST.get('category')
            
            if title:
                book.title = title
            if author:
                book.author = author
            if description is not None:
                book.description = description
            if stock is not None:
                book.stock = int(stock)
            if category is not None:
                book.category = category
            
            book.save()
            
            return JsonResponse({
                'code': 200,
                'info': '更新成功',
                'data': {
                    'id': book.id,
                    'title': book.title,
                    'author': book.author
                }
            })
            
        except Book.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '图书不存在'})
        except Exception as e:
            print(f"更新图书错误: {e}")
            return JsonResponse({'code': 500, 'info': '更新图书失败'})


class BookDeleteView(View):
    """删除图书API"""
    @require_permission(PERMISSIONS['BOOK_DELETE'])
    def delete(self, request, book_id):
        try:
            book = Book.objects.get(id=book_id)
            
            # 检查是否有未归还的借阅记录
            if BorrowRecord.objects.filter(book=book, is_returned=False).exists():
                return JsonResponse({'code': 400, 'info': '该图书有未归还的借阅记录，无法删除'})
            
            book.delete()
            return JsonResponse({'code': 200, 'info': '删除成功'})
            
        except Book.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '图书不存在'})
        except Exception as e:
            print(f"删除图书错误: {e}")
            return JsonResponse({'code': 500, 'info': '删除图书失败'})


# 借阅管理API
class BorrowBookView(View):
    """借阅图书API"""
    @require_permission(PERMISSIONS['BORROW_CREATE'])
    def post(self, request):
        try:
            # 从request中获取用户信息（通过装饰器添加）
            user = request.user
            book_id = request.POST.get('book_id')
            
            if not book_id:
                return JsonResponse({'code': 400, 'info': '图书ID不能为空'})
            
            book = Book.objects.get(id=book_id)
            
            # 检查图书库存
            if book.borrowed >= book.stock:
                return JsonResponse({'code': 400, 'info': '图书库存不足'})
            
            # 检查用户是否已借阅该图书
            if BorrowRecord.objects.filter(user=user, book=book, is_returned=False).exists():
                return JsonResponse({'code': 400, 'info': '您已借阅该图书，请先归还'})
            
            # 创建借阅记录
            borrow_record = BorrowRecord.objects.create(
                user=user,
                book=book
            )
            
            # 更新图书借阅数量
            book.borrowed += 1
            book.save()
            
            return JsonResponse({
                'code': 200,
                'info': '借阅成功',
                'data': {
                    'borrow_id': borrow_record.id,
                    'book_title': book.title,
                    'borrow_time': borrow_record.borrow_time.strftime('%Y-%m-%d %H:%M:%S')
                }
            })
            
        except Book.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '图书不存在'})
        except Exception as e:
            print(f"借阅图书错误: {e}")
            return JsonResponse({'code': 500, 'info': '借阅失败'})


class ReturnBookView(View):
    """归还图书API"""
    @require_permission(PERMISSIONS['BORROW_UPDATE'])
    def post(self, request):
        try:
            borrow_id = request.POST.get('borrow_id')
            
            if not borrow_id:
                return JsonResponse({'code': 400, 'info': '借阅记录ID不能为空'})
            
            borrow_record = BorrowRecord.objects.get(id=borrow_id)
            
            if borrow_record.is_returned:
                return JsonResponse({'code': 400, 'info': '该图书已归还'})
            
            # 更新借阅记录
            borrow_record.is_returned = True
            borrow_record.save()
            
            # 更新图书借阅数量
            book = borrow_record.book
            book.borrowed -= 1
            book.save()
            
            return JsonResponse({
                'code': 200,
                'info': '归还成功',
                'data': {
                    'book_title': book.title,
                    'return_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }
            })
            
        except BorrowRecord.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '借阅记录不存在'})
        except Exception as e:
            print(f"归还图书错误: {e}")
            return JsonResponse({'code': 500, 'info': '归还失败'})


class BorrowRecordListView(View):
    """借阅记录列表API"""
    @require_permission(PERMISSIONS['BORROW_VIEW'])
    def get(self, request):
        try:
            user_id = request.GET.get('user_id')
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            
            records = BorrowRecord.objects.all()
            
            if user_id:
                records = records.filter(user_id=user_id)
            
            # 按借阅时间倒序排列
            records = records.order_by('-borrow_time')
            
            # 分页
            paginator = Paginator(records, page_size)
            record_page = paginator.get_page(page)
            
            # 序列化数据
            record_list = []
            for record in record_page:
                record_list.append({
                    'id': record.id,
                    'user_id': record.user.id,
                    'username': record.user.username,
                    'book_id': record.book.id,
                    'book_title': record.book.title,
                    'borrow_time': record.borrow_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'is_returned': record.is_returned
                })
            
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': {
                    'records': record_list,
                    'total': paginator.count,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages
                }
            })
            
        except Exception as e:
            print(f"获取借阅记录错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取借阅记录失败'})


# 角色管理API
class RoleListView(View):
    """角色列表API"""
    @require_permission(PERMISSIONS['ROLE_VIEW'])
    def get(self, request):
        try:
            roles = Role.objects.all()
            role_list = []
            
            for role in roles:
                role_list.append({
                    'id': role.id,
                    'name': role.name,
                    'description': role.description,
                    'permissions': role.permissions,
                    'create_time': role.create_time.strftime('%Y-%m-%d %H:%M:%S')
                })
            
            return JsonResponse({
                'code': 200,
                'info': '获取成功',
                'data': role_list
            })
            
        except Exception as e:
            print(f"获取角色列表错误: {e}")
            return JsonResponse({'code': 500, 'info': '获取角色列表失败'})


class RoleCreateView(View):
    """创建角色API"""
    @require_permission(PERMISSIONS['ROLE_CREATE'])
    def post(self, request):
        try:
            name = request.POST.get('name')
            description = request.POST.get('description', '')
            permissions = request.POST.getlist('permissions')
            
            if not name:
                return JsonResponse({'code': 400, 'info': '角色名称不能为空'})
            
            if Role.objects.filter(name=name).exists():
                return JsonResponse({'code': 400, 'info': '角色名称已存在'})
            
            role = Role.objects.create(
                name=name,
                description=description,
                permissions=permissions
            )
            
            return JsonResponse({
                'code': 200,
                'info': '创建成功',
                'data': {
                    'id': role.id,
                    'name': role.name
                }
            })
            
        except Exception as e:
            print(f"创建角色错误: {e}")
            return JsonResponse({'code': 500, 'info': '创建角色失败'})


class UserRoleAssignView(View):
    """分配用户角色API"""
    @require_permission(PERMISSIONS['USER_UPDATE'])
    def post(self, request):
        try:
            user_id = request.POST.get('user_id')
            role_ids = request.POST.getlist('role_ids')
            
            if not user_id or not role_ids:
                return JsonResponse({'code': 400, 'info': '用户ID和角色ID不能为空'})
            
            user = User.objects.get(id=user_id)
            
            # 删除用户现有角色
            UserRole.objects.filter(user=user).delete()
            
            # 分配新角色
            for role_id in role_ids:
                role = Role.objects.get(id=role_id)
                UserRole.objects.create(user=user, role=role)
            
            return JsonResponse({
                'code': 200,
                'info': '角色分配成功'
            })
            
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '用户不存在'})
        except Role.DoesNotExist:
            return JsonResponse({'code': 404, 'info': '角色不存在'})
        except Exception as e:
            print(f"分配角色错误: {e}")
            return JsonResponse({'code': 500, 'info': '分配角色失败'})


class UserSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

